package com.sprcore.cas.server.support.login;

import java.security.GeneralSecurityException;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.apereo.cas.adaptors.jdbc.AbstractJdbcUsernamePasswordAuthenticationHandler;
import org.apereo.cas.authentication.HandlerResult;
import org.apereo.cas.authentication.PreventedException;
import org.apereo.cas.authentication.UsernamePasswordCredential;
import org.apereo.cas.authentication.principal.PrincipalFactory;
import org.apereo.cas.services.ServicesManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

public class QuerySprLoginAuthenticationHandler extends AbstractJdbcUsernamePasswordAuthenticationHandler {
	private static final Logger LOGGER = LoggerFactory.getLogger(QuerySprLoginAuthenticationHandler.class);

	private final JdbcTemplate jdbcTemplate;
	private final DataSource dataSource;
	private final String sql;
	private final String fieldPassword;
	private final String fieldExpired;
	private final String fieldDisabled;
	private final Map<String, Collection<String>> principalAttributeMap;

	public QuerySprLoginAuthenticationHandler(final String name, final ServicesManager servicesManager,
			final PrincipalFactory principalFactory, final Integer order, final DataSource dataSource, final String sql,
			final String fieldPassword, final String fieldExpired, final String fieldDisabled,
			final Map<String, Collection<String>> attributes) {
		super(name, servicesManager, principalFactory, order, dataSource);
		LOGGER.info("QuerySprLoginAuthenticationHandler#"+name);
		this.dataSource = dataSource;
		this.jdbcTemplate = new JdbcTemplate(dataSource);
		this.sql = sql;
		this.fieldPassword = fieldPassword;
		this.fieldExpired = fieldExpired;
		this.fieldDisabled = fieldDisabled; 
		this.principalAttributeMap = attributes; 
	}

	@Override
	protected HandlerResult authenticateUsernamePasswordInternal(UsernamePasswordCredential credential,
			String originalPassword) throws GeneralSecurityException, PreventedException {

		final Map<String, Object> attributes = new LinkedHashMap(this.principalAttributeMap.size());
		final String username = credential.getUsername();
		final String password = credential.getPassword();
		LOGGER.info("-credential.username=" + username);
		LOGGER.info("-credential.password=" + password);
		LOGGER.info("-originalPassword=" + originalPassword);

		return createHandlerResult(credential, this.principalFactory.createPrincipal(username, attributes), null);
	}

	@Override
	protected DataSource getDataSource() {
		return super.getDataSource();
	}

	@Override
	protected JdbcTemplate getJdbcTemplate() {
		return super.getJdbcTemplate();
	}

}
